'''
TCP Echo Server
'''

import socket
import sys
import struct
import base64
import time
import queue
import threading

read_queue = queue.Queue()     # 接受消息队列


def recv_msg_handle():
    global read_queue
    t = time.perf_counter()
    count = 0
    while True:
        body = read_queue.get()
        content, img1, img2 = struct.unpack(
            '>%ds%ds%ds' % (content_size, img_size1, img_size2), body)
        count += 1
        if count % 10 == 0:
            print(f'coast:{time.perf_counter() - t:.8f}s')

if __name__ == '__main__':
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    msg_thread = threading.Thread(target=recv_msg_handle)
    msg_thread.setDaemon(True)
    msg_thread.start()

    server_socket.bind(('192.21.1.43', 8701))
    server_socket.listen(0)
    client_socket, addr = server_socket.accept()
    client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 10*1024*1024)

    while True:
        head = client_socket.recv(16)
        id, content_size, img_size1, img_size2 = struct.unpack('>IIII', head)
        body = b''
        body_length = content_size+img_size1+img_size2
        while len(body) < body_length:
            data = client_socket.recv(body_length - len(body))
            body += data
        read_queue.put(body)

